/*************************************** Copyright ****************************** 
  * FileName   : Encoder_Func.c   
  * Version    : v1.0		
  * Author     : --			
  * Date       : 2022-11-14         
  * Description:    
  * Function List:  
  	1. ....
  	   <version>: 		
  <modify staff>:
  		  <data>:
   <description>:  
  	2. ...
********************************************************************************/
 
/*include----------------------------------------------------------------------*/
#include "Encoder_Func.h"

/*define-----------------------------------------------------------------------*/


/*variate----------------------------------------------------------------------*/
Encoder_TypeDef Enc_1;

/*statement--------------------------------------------------------------------*/


/*Function prototype Begin*****************************************************/



HAL_StatusTypeDef Encoder_Init(Encoder_TypeDef *Enc,TIM_HandleTypeDef *htim)
{
	HAL_StatusTypeDef Status;
	Enc->Tim_HandleTypeDef = htim;		//定时器
	Enc->direction = 1;								//正方向
	Enc->count_32 = 0;								//计数值
	Enc->update_value = 0;						//更新值
	
	Enc->key_short = 0;								//按键短按
	Enc->key_long  = 0;								//按键长按
	Enc->Long_press_time = 300;				//按键长按时间
	
	Status = HAL_TIM_Encoder_Start(htim,TIM_CHANNEL_ALL);					//开启编码器定时器
	
	
	return Status;
}
	
void Encoder_count(Encoder_TypeDef *Enc,uint32_t count,uint32_t DT_ms)
{
	static uint32_t last_cnt;
	count=count>>1;
	if(last_cnt!=count)
	{
		int Dcnt = count-last_cnt;
		if		  (Dcnt>(int)DT_ms*4)				Dcnt = (0xffff/2) - Dcnt -1;
		else if((-Dcnt)>(int)DT_ms*4)			Dcnt = (0xffff/2) + Dcnt +1;
		last_cnt = count;
		Dcnt = Dcnt * Enc->direction;
		Enc->update_value += Dcnt;
		Enc->count_32 += Dcnt;
	}	
}


void Encoder_Key_scan(Encoder_TypeDef *Enc,uint32_t Key_state)
{
	static uint32_t last_state = 1;
	static uint32_t Press_time = 0;
	static uint8_t Long_press_flag = 0;
	if(last_state!=Key_state)
	{
		last_state = Key_state;
		if(Key_state)
		{
			if(!Long_press_flag)				Enc->key_short++;
			else Long_press_flag = 0;
		}
		else
		{
			Press_time = HAL_GetTick();			
		}
	}
	if(Key_state == 0)	//长按判断
	{
		if(Long_press_flag == 0)
		{
			if((HAL_GetTick()-Press_time) > Enc->Long_press_time)
			{
				Long_press_flag = 1;
				Enc->key_long++;
			}
		}
	}
}









/*Function prototype End*******************************************************/














